﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace MailRuWrapper.Server
{

    public class DateTimeConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        }

        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        {
            if (!String.IsNullOrEmpty(reader.Value as String))
            {
                return ((string) reader.Value).ToDateTime();
            }

            if (reader.TokenType == JsonToken.Integer)
            {
                return new DateTime(1970, 1, 1) + new TimeSpan(((Int64) reader.Value)*TimeSpan.TicksPerSecond);
            }
            return null;
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }

    public class BooleanConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((bool)value) ? "1" : "0");
        }

        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        {
            return (reader.Value as String) == "1";
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }

    public class RefererConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((RefererTypes)value).GetAttributes<DefaultValueAttribute>().Single().Value as string);
        }

        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        {
            return (reader.Value as String).ToRefererType();
        }

        public override bool CanConvert(Type objectType)
        {
            return true;
        }
    }
}
